from appium import webdriver
from selenium.webdriver.common.by import By as AppiumBy
import time
import logging
import os
from datetime import datetime

# 配置日志

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',filename ='ota.log')


def initialize_driver():
    desired_caps = {
        "platformName": "Android",        # 操作系统
        "platformVersion": "7.1.2",          # 安卓版本
        "deviceName": "127.0.0.1:62001",      # 设备名称
        "appPackage": "com.suntek.smartlife",   # 目标App包名
        "appActivity": "com.smart.ThingSplashActivity",  # 启动Activity
        "noReset": False,                  # 不要重置App状态
        "automationName": "UiAutomator2", # 自动化引擎
        "newCommandTimeout": 1200
    }
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
    driver.implicitly_wait(10)
    return driver
def take_screenshot(driver, name):
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    screenshot_name = f"{name}_{timestamp}.png"
    screenshot_path = os.path.join(os.getcwd(), screenshot_name)
    driver.save_screenshot(screenshot_path)
    logging.info(f"截图已保存: {screenshot_path}")

def login(driver):
    try:
        logging.info("开始登录流程")
        agree_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/positiveButton")
        agree_btn.click()
        
        logging.info("点击继续使用按钮")
        ctu_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
        ctu_btn.click()
       
        
        logging.info("点击确认按钮")
        login_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/btn_login")
        login_btn.click()
        
        
        logging.info("输入用户名")
        input_name = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/et_text")
        input_name.send_keys("17279412354")
       
        
        logging.info("输入密码")
        password_input = driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.ScrollView/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout[2]/android.view.ViewGroup/android.widget.EditText")
        password_input.send_keys("cg123123")
        
        logging.info("同意协议")
        agr_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/cb_agreement")
        agr_btn.click()
        
        logging.info("点击登录按钮")
        dl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_text")
        dl_btn.click()
        time.sleep(5)

        logging.info("点击进入按钮")
        jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorX")
        jl_btn.click()
        
        logging.info("关闭位置权限")
        ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
        ys_btn.click()
        time.sleep(20)
        
    except Exception as e:
        logging.error(f"执行过程中出现异常: {str(e)}")
        take_screenshot(driver, "login_error")
        driver.quit()

def upgrade(driver):
    try:
        while True:
            try:
                if driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm"):
                    logging.info("开始升级流程")
                    for i in range(100):
                        logging.info(f"开始第 {i+1} 次升级")
                        upgrate_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
                        upgrate_btn.click()
                        time.sleep(2)
                        
                        new_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_operation")
                        new_btn.click()
                        
                        staup_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
                        staup_btn.click()
                        
                        logging.info("升级中")
                        for _ in range(70):  # 每次等待10秒
                            time.sleep(10)
                            logging.info("升级中...")
                        # time.sleep(700)
                            if driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[3]/android.view.ViewGroup[4]/android.view.ViewGroup[1]']/android.view.View") :
                                logging.info("升级成功")
                        logging.info("检测是否有升级按钮")
                        time.sleep(700)
                        # lkown_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv")
                        # lkown_btn.click()
                        # 返回
                        back_btn = driver.find_element(AppiumBy.XPATH, "//android.view.ViewGroup[@content-desc='TopBar_Btn_Back']/android.view.View")      
                        back_btn.click()
                        time.sleep(2)

                        logging.info("点击进入按钮")
                        jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorY")
                        jl_btn.click()
                        time.sleep(8)
                        
                        logging.info("关闭位置权限")
                        ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
                        ys_btn.click()
                        time.sleep(20)
                else:
                    raise Exception("没有找到升级确认按钮")
            except Exception as e:
                logging.info("进入设备升级")
                bl_btn = driver.find_element(AppiumBy.XPATH, "//android.view.ViewGroup[@content-desc='TopBar_Btn_RightItem']/android.view.View")
                bl_btn.click()
                sbota_btn = driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/androidx.recyclerview.widget.RecyclerView/android.widget.RelativeLayout[7]")#com.suntek.smartlife:id/menu_list_sub_title
                sbota_btn.click()
                if driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_operation"):
                    new_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_operation")
                    new_btn.click()
                    staup_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
                    staup_btn.click()
                    logging.info("升级中")
                    for _ in range(70):  # 每次等待10秒
                            time.sleep(10)
                            logging.info("升级中...")
                            if driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[3]/android.view.ViewGroup[4]/android.view.ViewGroup[1]']/android.view.View") :
                                logging.info("升级完成")
                    time.sleep(700)
                else:    
                    back_btn = driver.find_element(AppiumBy.XPATH, "//android.view.ViewGroup[@content-desc='TopBar_Btn_Back']/android.view.View")      
                    back_btn.click()
                    time.sleep(2)
                # lkown_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv")
                # lkown_btn.click()
                # time.sleep(3)
                # 返回
                back_btn = driver.find_element(AppiumBy.XPATH, "//android.view.ViewGroup[@content-desc='TopBar_Btn_Back']/android.view.View")      
                back_btn.click()
                time.sleep(2)

                logging.info("点击进入按钮")
                jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorY")
                jl_btn.click()
                driver.implicitly_wait(10)
                
                logging.info("关闭位置权限")
                ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
                ys_btn.click()
                time.sleep(20)
            
    except Exception as e:
        logging.error(f"执行过程中出现异常: {str(e)}")
        take_screenshot(driver, "login_error")
    finally:
        driver.quit()
        logging.info("重新初始化驱动并重试")
        driver = initialize_driver()
        login(driver)
        upgrade(driver)

if __name__ == "__main__":
    driver = initialize_driver()
    login(driver)
    upgrade(driver)